// multi thread to calculate the result
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>

#define N_NUM 1000000
#define THREAD_NUM 1

struct sum_thread_s
{
    long long sum;  // sum calculated by the thread
    pthread_t tid;
    int task_start;
    int task_end;
} threads[THREAD_NUM];

int a[N_NUM];
int arg[THREAD_NUM];
long long sum;

void *
calc_sub_sum(void * arg)
{
    struct sum_thread_s * sub_arg = (struct sum_thread_s *)arg;
    for(int i = sub_arg->task_start; i<sub_arg->task_end;i++)
    {
        sub_arg->sum += a[i];
    }
    return NULL;
}

int main()
{
    for(int i = 0; i<N_NUM; i++)
        a[i] = i;
    struct timespec start,end;
    clockid_t cpu_clock;
    clock_getcpuclockid(0,&cpu_clock);
    clock_gettime(cpu_clock,&start);

    // create threads
    int num_per_thread = N_NUM / THREAD_NUM;
    for(int i = 0; i<THREAD_NUM-1;i++)
    {
        threads[i].sum = 0;
        threads[i].task_start = i * num_per_thread;
        threads[i].task_end = (i+1) * num_per_thread;
        pthread_create(&(threads[i].tid),NULL,calc_sub_sum,threads + i);
    }
    threads[THREAD_NUM - 1].sum = 0;
    threads[THREAD_NUM - 1].task_start = (THREAD_NUM - 1)*num_per_thread;
    threads[THREAD_NUM - 1].task_end = N_NUM;
    pthread_create(&(threads[THREAD_NUM - 1].tid),NULL,calc_sub_sum,threads + THREAD_NUM - 1);

    // wait thread to end
    for(int i = 0; i< THREAD_NUM ; i++)
    {
        pthread_join(threads[i].tid,NULL);
    }

    // calculate the sum
    sum = 0;
    for(int i = 0; i<THREAD_NUM;i++)
    {
        sum += threads[i].sum;
    }

    // for(int i = 0; i<N_NUM; i++)
    //     sum += a[i];


    clock_gettime(cpu_clock,&end);
    // printf("get %lld, used %ld ns + %lds \n",sum,end.tv_nsec-start.tv_nsec
    //     ,(long)end.tv_sec - (long)start.tv_sec);

    printf("%ld",end.tv_nsec-start.tv_nsec);
    return 0;
}